﻿using HandyControl.Controls;
using HandyControl.Tools;
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MessageBox = HandyControl.Controls.MessageBox;

namespace MongoDBManager
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : BlurWindow
    {
        MongoUtil ExportUtil = new MongoUtil();
        MongoUtil ImportUtil = new MongoUtil();

        List<Brush> Brushs = new List<Brush>();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }



        private async void ExportBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!ExportUtil.IsSuccess)
            {
                MessageBox.Error("导出数据库没有连接!");
                return;
            }
            Task.Run(() =>
            {

                ShowLog("正在导出数据···");

                List<string> doucuments = ExportUtil.GetDoucuments();

                string dbname = ExportUtil.GetDatabaseName();

                string dbdir = FileUtil.CreateDataBaseDir(dbname);

                foreach (var doc in doucuments)
                {
                    string path = dbdir + "\\" + doc + ".json";

                    List<BsonDocument> bsonDocuments = ExportUtil.GetDoucument(doc);


                    StreamWriter writer = new StreamWriter(File.Create(path));

                    foreach (var bson in bsonDocuments)
                    {

                        string json = bson.ToJson();

                        writer.WriteLine(json);

                    }

                    writer.Close();
                }

                ShowLog("导出完毕!输出目录:" + dbdir);
            });
        }

        private void ShowLog(string txt)
        {
            this.Dispatcher.Invoke(() =>
            {
                Gress.Visibility = Visibility.Visible;
                Gress.Content = txt;
                if (txt.Contains("完毕"))
                {
                    Loading.Visibility = Visibility.Hidden;
                }
                else
                {
                    Loading.Visibility = Visibility.Visible;
                }
            });
        }

        private void ImportBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!ImportUtil.IsSuccess)
            {
                MessageBox.Error("导入数据库没有连接!");
                return;
            }
            System.Windows.Forms.FolderBrowserDialog openFileDialog = new System.Windows.Forms.FolderBrowserDialog(); //选择文件夹
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                string dir = openFileDialog.SelectedPath;
                string[] dirs = dir.Substring(dir.LastIndexOf("\\") + 1).Split("_");
                if (dirs.Length == 2)
                {
                    string dsname = dirs[0];
                    string dname = ImportUtil.GetDatabaseName();

                    if (!ImportUtil.GetListDatabaseNames().Contains(dname))
                    {

                        Task.Run(() =>
                        {

                            ShowLog("正在导入数据···");

                            string[] files = FileUtil.GetFiles(dir);

                            foreach (var file in files)
                            {
                                string doc = file.Substring(file.LastIndexOf("\\") + 1).Replace(".json", "");

                                ImportUtil.CreateCollection(doc);
                                string[] lines = File.ReadAllLines(file);

                                foreach (var line in lines)
                                {

                                    BsonDocument bjson = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(line);

                                    ImportUtil.InsertDoucument(doc, bjson);
                                }

                            }

                            ShowLog("导入完毕!");
                        });
                    }
                    else
                    {
                        MessageBox.Error($"已有{dname}数据库,不能导入,请输入不存在的数据库,将自动创建数据库!");
                    }


                }
                else
                {
                    MessageBox.Error("选择的目录不是输出目录");
                }


            }
        }

        private void ExportBtnTest_Click(object sender, RoutedEventArgs e)
        {

            ExportUtil = new MongoUtil();
            if (ExportUtil.TestConnection(ExportUrl.Text))
            {
                ExportStatus.Fill = Brushes.Green;
                ShowLog("导出数据库连接成功!");
            }
            else
            {
                ExportStatus.Fill = Brushes.Red;
                ShowLog("导出数据库连接失败!");
            }
            Loading.Visibility = Visibility.Hidden;
        }

        private void ImportBtnTest_Click(object sender, RoutedEventArgs e)
        {
            ImportUtil = new MongoUtil();
            if (ImportUtil.TestConnection(ImportUrl.Text))
            {
                ImportStatus.Fill = Brushes.Green;
                ShowLog("导入数据库连接成功!");
            }
            else
            {
                ImportStatus.Fill = Brushes.Red;
                ShowLog("导入数据库连接失败!");
            }
            Loading.Visibility = Visibility.Hidden;
        }
    }
}
